import router from '@/router'
import axios from 'axios'
import { getToken, removeToken } from './token'
import { ElMessage } from 'element-plus'
import { API_BASE_URL } from './url'

const request = axios.create({
    baseURL: API_BASE_URL,
})

request.interceptors.request.use(
    (config) => {
        const token = getToken()
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

request.interceptors.response.use(
    (response) => {
        if (
            response.data.success === false &&
            !response.data.noAlert &&
            response.data.msg
        ) {
            ElMessage.error(response.data.msg)
        }
        return response.data
    },
    (error) => {
        const { status } = error.response

        if (status === 401) {
            router.push('/login')
            removeToken()
        }

        return Promise.reject(error)
    }
)

export default request
